package com.csxy.systemmanager.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.netty.util.internal.StringUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.UUID;

public class JwtUtil {
//过期时间 默认为24小时
    private static final long DEFAULT_TIME = 1000 * 60 * 60 * 24;
    //密钥
    private static final String SECRET = "SAADAD222SSDDasdad1315AA1J154";

    //生成token字符串的方法
    public static String createJwt(String id){
        String token = Jwts.builder().
                //头信息
                setHeaderParam("typ", "JWT").
                setHeaderParam("alg", "HS256").
                //负载内容
                claim("userId", id).setSubject("jwt-user").
                //过期时间设置
                setExpiration(new Date(System.currentTimeMillis() + DEFAULT_TIME)).
                setId(UUID.randomUUID().toString())
                //签名
                .signWith(SignatureAlgorithm.HS256, SECRET).
                //连接返回
                compact();
        return token;
    }
    //解析token字符串的方法 得到userID
    public static String getUserIDbyToken(HttpServletRequest request){
        //得到token
        String token = request.getHeader("token");
        //解析操作
        if(StringUtil.isNullOrEmpty(token)) return "";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        String userId = (String)claims.get("userId");
        return  userId;
    }
    public static String getUserIDbyToken(String token){
        //解析操作
        if(StringUtil.isNullOrEmpty(token)) return "";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        String userId = (String)claims.get("userId");
        return  userId;
    }
    //检索token是否存在
    public static boolean checkToken(HttpServletRequest request){
        //得到token
        String token = request.getHeader("token");
        //token的判断
        if(StringUtil.isNullOrEmpty(token)) return false;
        try{
            Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token);
        }catch (Exception e){
            return false;
        }
        return true;
    }
    //检索token是否存在
    public static boolean checkToken(String token){
        //token的判断
        if(StringUtil.isNullOrEmpty(token)) return false;
        try{
            Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token);
        }catch (Exception e){
            return false;
        }
        return true;
    }

}
